|
|
|
|
|
|
|
also result in six columns. If there is not an equal number of columns on each side of a UNION query, you receive an SQL error message. |
|
|
|
|
|
|
|
|
You can also use UNION queries on the same table. The following SQL statement (see Figure 8.32) shows how you can use SQL to return the top-selling titles and the bottom-selling titles in the same result set: |
|
|
|
|
|
|
|
|
SELECT SUM(Sales) AS TotSales,Title FROM BookSales
GROUP BY Title HAVING SUM(Sales)>4000
UNION
SELECT SUM(Sales) AS TotSales,Title FROM BookSales
GROUP BY Title HAVING SUM(Sales)<1000
ORDER BY TotSales |
|
|
|
|
|
|
|
|
Figure 8.32.
Using UNION on the same data table. |
|
|
|
|
|
|
|
|
You can use Visual Basic stored queries (QueryDefs) as replacements for the complete SQL statement on either side of a UNION keyword. You can also link several SQL queries together with successive UNION keywords. |
|
|
|
|
|
|
|
|
Crosstab Queries with TRANSFORM_PIVOT |
|
|
|
|
|
|
|
|
The last SQL statement covered today is the TRANSFORM_PIVOT statement. This is a very powerful SQL tool that enables you to create result sets that contain summarized data in a form known as a crosstab query. Instead of trying to explain a crosstab query, let's look at a sample problem. |
|
|
|
|
|
|
|
|
Suppose you have a data table that contains information on book titles and sales by quarter (sound familiar?). You have been asked to produce a view set that lists each book title down the left side and each quarter across the top with the sales figures for each quarter to the right of the book title. The only problem is that your data table has a single record for each quarter for each book. For example, if book A has sales in three quarters this year, you have three rows |
|
|
|
|
|